package com.jcl.recruit.wechat.service;

import com.jcl.core.security.ShareUserToken;
import com.jcl.core.utils.CollectionUtils;
import com.jcl.core.utils.HttpRequest;
import com.jcl.recruit.attach.vo.AttachmentPhotoVo;
import com.jcl.recruit.core.constants.UserExternalLoginConstant;
import com.jcl.recruit.register.service.RegisterResult;
import com.jcl.recruit.register.service.RegisterVo;
import com.jcl.recruit.register.service.impl.AbstractJclRegisterImpl;
import com.jcl.recruit.user.logic.UserExternalAccessLogic;
import com.jcl.recruit.user.model.User;
import com.jcl.recruit.user.model.UserExternalAccess;
import com.jcl.recruit.wechat.logic.WechatCommonLogic;
import com.jcl.recruit.wechat.utils.WechatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

@Service
public class WechatRegisterService extends AbstractJclRegisterImpl {

    @Autowired
    private UserExternalAccessLogic userExternalAccessLogic;

    @Autowired
    private WechatCommonLogic wechatCommonLogic;

    /* *
     * @Author yyliu
     * @Description 微信 企业注册
     * @Date 12:59 2018/9/14
     * @Param [vo]
     * @return com.example.service.register.RegisterResult
     **/
    public RegisterResult corpRegister(RegisterVo vo) {
        // 注册企业
        RegisterResult result = super.registerCorp(vo);
        if (result.hasError()) {
            return result;
        }
        User user = result.getUser();
        List<UserExternalAccess> accessList = userExternalAccessLogic.findListByExternalKey(vo.getUserKey(),
                UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT,
                UserExternalLoginConstant.USER_ACCESS_STATUS_USED);

        if (CollectionUtils.isNotEmpty(accessList)) {
            UserExternalAccess access = accessList.get(0);
            access.setId(null);

            // 清除默认使用企业
            userExternalAccessLogic.changeUseStatusToInvalid(
                    vo.getUserKey(), UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT);

            access.setCorpCode(user.getCorpCode());
            access.setUserId(user.getId());
            access.setStatus(UserExternalLoginConstant.USER_ACCESS_STATUS_USED);
            access.setModifyTime(new Date());
            access.setCreateTime(new Date());
            access.setUsername(access.getExternalKey()
                    + UserExternalLoginConstant.USER_ACCESS_SPLIT + user.getCorpCode());
            userExternalAccessLogic.add(access);
        }
        return result;
    }

    /* *
     * @Author yyliu
     * @Description 微信邀请 用户注册
     * @Date 12:59 2018/9/14
     * @Param [vo]
     * @return com.example.service.register.RegisterResult
     **/
    public RegisterResult userRegister(RegisterVo vo) {
        RegisterResult result = new RegisterResult();
        ShareUserToken tokenInfo = ShareUserToken.decodeInviteToken(vo.getAccessKey());
        User user = new User();
        user.setUsername(vo.getEmail());
        user.setRealname(vo.getUsername());
        user.setCorpCode(tokenInfo.getCorpCode());
        user.setEmail(vo.getEmail());
        user.setInviteUserId(Integer.parseInt(tokenInfo.getUserId()));

        try {
            user = userRegisterLogic.applyRegisterUser(user);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        UserExternalAccess access = userExternalAccessLogic.findOne(Integer.parseInt(vo.getAccessId()));
        if (null != access) {

            // 清除默认使用企业
            userExternalAccessLogic.changeUseStatusToUnused(
                    access.getExternalKey(), UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT);

            access.setCorpCode(user.getCorpCode());
            access.setUserId(user.getId());
            access.setUsername(access.getExternalKey()
                    + UserExternalLoginConstant.USER_ACCESS_SPLIT + user.getCorpCode());
            // 默认使用注册企业
            access.setStatus(UserExternalLoginConstant.USER_ACCESS_STATUS_USED);
            access.setModifyTime(new Date());
            userExternalAccessLogic.updateAccess(access);

            // 获取登录的微信用户信息
            WechatUtils.WechatUserInfo userInfo = WechatUtils.getUserInfoObject(WechatUtils.getAccessToken(),
                    access.getExternalKey());

            byte[] b = HttpRequest.getByte(userInfo.getHeadimgurl());
            AttachmentPhotoVo photoVo = new AttachmentPhotoVo();
            photoVo.setBytes(b);
            photoVo.setFileName(userInfo.getOpenid());

            // 更换头像
            wechatCommonLogic.updateUserHead(photoVo, user.getId(), user.getCorpCode());

        }
        result.setUser(user);
        return result;
    }
}
